package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    OrdersService ordersService;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    UserService userService;
    @Value("F:\\java\\workspace\\reggie_waimai")
    private String outPath;

//    去支付，生成订单
    @PostMapping("/submit")
    @Transactional
    public R<String> submit(Orders orders){
        //改两个表 一个为订单orders 一个为订单明细orderdetail
        //利用购物车shoopingcart 可以把对应的数据封装到orderDetail数据中（其中的orderid从order获取）
        //将addressbook,shoppingcart对应的数据address/?封装到order中
        //order金额从orderdetai中获取 总金额=（商品1数量*商品1单价+商品2数量*商品2单价）

        //获取用户userid
        Long userid = BaseContext.getCurrentId();
        //查找对应的user
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId,userid);
        User userone = userService.getOne(lambdaQueryWrapper);
        //查询购物车 select* from shoopingcart where userid=?
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userid);
        //查询对应的购物车
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper);
        //判断购物车是否为空
        if(shoppingCartList==null || shoppingCartList.size()==0){
           throw new CustomException("购物车为空，不能下单！！！");
        }
         //查询默认地址 selecr * from addressbook where userid=? and isdefault=1
        LambdaQueryWrapper<AddressBook> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(AddressBook::getUserId,userid);
        wrapper1.eq(AddressBook::getIsDefault,1);
        //查询对应的地址
        AddressBook addressBookone = addressBookService.getOne(wrapper1);
        //判断地址是否为空
        if(addressBookone==null){
            throw new CustomException("地址为空,不能下单！！！");
        }
        //现在将对应的数据封装到orderdetail
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        //IDwork工具类生成order中number  id
        long orderId = IdWorker.getId();
        //总价
        BigDecimal amount = new BigDecimal(0);
        //集合便利挨个封装
        for (ShoppingCart shoppingCart : shoppingCartList) {
            //new 一个orderrdteail进行封装
            OrderDetail orderDetail = new OrderDetail();
            //图片orderDetail
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            //总价=单价*数量
            //数量
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            //单价
            BigDecimal price = shoppingCart.getAmount();
            orderDetail.setAmount(price.multiply(number));
            amount = amount.add(orderDetail.getAmount());
            //将orderDetail数据添加到表中
            orderDetailService.save(orderDetail);
        }
        //将orders数据封装
//        orders.setId(orderId);
        //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(1);
        orders.setUserId(userid);
        orders.setNumber(String.valueOf(orderId));
        orders.setAddressBookId(addressBookone.getId());
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //结账时间
        orders.setCheckoutTime(LocalDateTime.now());
       //总价
        orders.setAmount(amount);
        //订单addressBookone手机号
        orders.setPhone(addressBookone.getPhone());
        //username
        orders.setUserName(userone.getName());
        ////省+市+区域+详细地址
//        orders.setAddress(addressBookone.getDetail());
        orders.setAddress(
               (addressBookone.getProvinceName()==null ?"":addressBookone.getProvinceName())
               +(addressBookone.getCityName()==null ?"":addressBookone.getCityName())
               +(addressBookone.getDistrictName()==null ?"":addressBookone.getDistrictName())
               +(addressBookone.getDetail()==null ?"":addressBookone.getDetail())
        );
        ordersService.save(orders);
        //删除对应的购物车数据
        shoppingCartService.remove(wrapper);
       return R.success("下单成功！！！");

    }

    //分页查询订单
//    @GetMapping("/userPage")
//    public R<Page> page(Integer page,Integer pageSize){
//        Page<Orders> ordersPage = new Page<>(page,pageSize);
//        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
//        ordersService.page(ordersPage,wrapper);
//        return R.success(ordersPage);
//    }
        @GetMapping("/userPage")
    public R<Page> page(Integer page,Integer pageSize){
        Page<Orders> ordersPage = new Page<>(page,pageSize);

        Page<OrderDto> orderDtoPage = new Page<>();

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Orders::getUserId,BaseContext.getCurrentId());

        ordersService.page(ordersPage,wrapper);

        BeanUtils.copyProperties(ordersPage,orderDtoPage);

        List<Orders> records = ordersPage.getRecords();



        ArrayList<OrderDto> orderDtos = new ArrayList<>();

            for (Orders record : records) {
                OrderDto orderDto = new OrderDto();
               //order中 id
                Long id = record.getId();

                OrderDetail orderDetail = orderDetailService.getById(id);

                String name = orderDetail.getName();

            }


        return R.success(orderDtoPage);
    }

   @GetMapping("/page")
    public R<Page> page1(Integer page, Integer pageSize, String number, String beginTime,String endTime){
//      SELECT COUNT(*) FROM orders WHERE (number LIKE ? AND checkout_time BETWEEN ? AND ?)
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(number!=null&&number!="",Orders::getNumber,number).between(beginTime!=null&&endTime!=null,Orders::getCheckoutTime,beginTime,endTime);
        ordersService.page(ordersPage,wrapper);
        return R.success(ordersPage);
    }
   //订单明细中新增一个Excel导出功能

    @GetMapping("/export")
    public R<String> export() {
        List<Orders> list = ordersService.list();
        String fileName=outPath+"瑞吉订单统计表"+System.currentTimeMillis()+".xlsx";
        EasyExcel.write(fileName,Orders.class).sheet("瑞吉点餐").doWrite(list);
        return R.success("导出成功！！！");
    }
}
